<?php
/**
 * @author lsx <karascanvas@qq.com>
 */

namespace library\tencent\wechat\admin_wechat;
use library\tencent\wechat\admin_wechat\Settings;
use library\tencent\wechat\common\WechatMP;

class WechatMpService
{
    public static function getAccessToken()
    {
        $key = 'wechat_mp_access_token';
        $data = Settings::get($key);
        if ($data === null || $data['expires'] < time()-100) {
            $cfg = Settings::get('wechat_mp_config');
            $result = WechatMP::getToken($cfg['app_id'], $cfg['secret']);

            if ($result->success()) {
                $data = [
                    'access_token' => $result->getField('access_token'),
                    'expires'      => time() + $result->getField('expires_in'),
                ];
                Settings::set($key, $data);
            } else {
                return null;
            }
        }
        return $data['access_token'];
    }


}